﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.Threading;

namespace CommonGUI
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;
        }

        private void button1_Click(object sender, EventArgs e)
        {

            Thread doCMDThread = new Thread(new ThreadStart(doCMD));
            doCMDThread.Start();
           
        }
        private void doCMD()
        {
            Process process = new Process();

            process.StartInfo.FileName = "cmd.exe";

            process.StartInfo.UseShellExecute = false;   // 是否使用外壳程序 

            process.StartInfo.CreateNoWindow = true;   //是否在新窗口中启动该进程的值 

            process.StartInfo.RedirectStandardInput = true;  // 重定向输入流 

            process.StartInfo.RedirectStandardOutput = true;  //重定向输出流 

            process.StartInfo.RedirectStandardError = true;  //重定向错误流 
            process.StartInfo.Arguments = "/c " + textBox1.Text;
            //textBox2.AppendText(textBox1.Text + "\n\r");
            textBox1.Text = "";
            

            try
            {
                process.Start();
                char[] enter = { '\r', '\n' };
                process.OutputDataReceived += (s, _e) => { if (_e.Data != null)textBoxStatus.AppendText(_e.Data.Trim(enter) + "\n\r"); };
                process.ErrorDataReceived += (s, _e) => { if (_e.Data != null)textBoxStatus.AppendText(_e.Data.Trim(enter) + "\n\r"); };

                //当EnableRaisingEvents为true，进程退出时Process会调用下面的委托函数

                process.EnableRaisingEvents = true;

                process.BeginOutputReadLine();

                process.BeginErrorReadLine();

                process.WaitForExit();

            }

            catch (Exception ex)
            {

                Console.WriteLine(ex.Message);

            }
        }

        private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '\r')
            {
                button1_Click(sender, e);
            }
        }
    }
}
